<template>
    <div class="content-box">
        <!-- 搜索地址 -->
        <div class="search-container">
            <div class="input-container">
                <el-form :model="myForm" ref="myForm" label-width="85px" class="my-el-form">
                    <el-form-item label="车场名称：" prop="parkValue">
                        <el-input v-model="myForm.parkValue" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="button-container">
                <el-button @click="handleReset('myForm')">重置</el-button>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="primary" @click="handAdd">+ 新增</el-button>
            </div>
        </div>
        <!-- 展示表格 -->
        <div class="container">
            <div class="table-container">
                <el-table ref="Table1" :data="list" style="width: 100%" border>
                    <el-table-column label="车场名称" align="center">
                        <template slot-scope="scope">{{ scope.row.parkingLotName }}</template>
                    </el-table-column>
                    <el-table-column label="经营状态" align="center" prop="operateStatus" :formatter="formatOpe"> </el-table-column>
                    <el-table-column label="所属业态" align="center" prop="oneBusinessType" :formatter="formatBus"> </el-table-column>
                    <el-table-column label="车场地址" align="center">
                        <template slot-scope="scope">{{ scope.row.address || '-' }}</template>
                    </el-table-column>
                    <el-table-column label="建设时间" align="center">
                        <template slot-scope="scope">{{ scope.row.buildDate }}</template>
                    </el-table-column>
                    <el-table-column label="运营时间" align="center">
                        <template slot-scope="scope">{{ scope.row.operateDate }}</template>
                    </el-table-column>

                    <el-table-column label="操作" align="center" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleUpdate(scope.$index, scope.row)">编辑</el-button>
                            <!-- <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="pagination-area">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page.sync="listQuery.pageNum"
                    :page-size="listQuery.pageSize"
                    :page-sizes="[10, 20, 50]"
                    :total="total"
                >
                </el-pagination>
            </div>
        </div>

        <!-- 新增弹框 -->
        <el-dialog title="车场配置" :visible.sync="dialogFormVisible" width="800px" @close="closeModal">
            <el-tabs tab-position="left" v-model="activeTab" :before-leave="changeTab">
                <el-tab-pane label="车场信息" name="parkInfo">
                    <el-form ref="modalForm" :rules="modalRules" :model="modalForm" label-width="120px" class="park-info">
                        <!-- 车场信息配置 -->
                        <el-form-item label="车场名称：" prop="parkingLotName">
                            <el-input v-model="modalForm.parkingLotName" autocomplete="off" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="经营状态：" prop="operateStatus">
                            <el-select v-model="modalForm.operateStatus" placeholder="请选择">
                                <el-option v-for="item in operateStatusOpt" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属业态：" prop="oneBusinessType">
                            <el-select v-model="modalForm.oneBusinessType" placeholder="请选择">
                                <el-option v-for="item in firstBussinessOpt" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="车场地址：" prop="address">
                            <el-input v-model="modalForm.address" autocomplete="off" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="建设时间：" prop="buildDate">
                            <el-date-picker
                                type="date"
                                placeholder="选择日期"
                                v-model="modalForm.buildDate"
                                style="width: 100%"
                                value-format="yyyy-MM-dd"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="运营时间：" prop="operateDate">
                            <el-date-picker
                                type="date"
                                placeholder="选择日期"
                                v-model="modalForm.operateDate"
                                style="width: 100%"
                                value-format="yyyy-MM-dd"
                            ></el-date-picker>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="通道信息" name="drivewayInfo">
                    <el-form ref="drivewayModal" :model="drivewayModal" label-width="80px">
                        <!-- 通道配置 -->
                        <el-card class="box-card" style="margin-bottom: 20px">
                            <div class="driveway-title">入口通道</div>
                            <div class="driveway-item" v-for="(item, index) in drivewayModal.entryDriveways" :key="index">
                                <el-form-item
                                    :label="'入口' + (Number(index) + 1)"
                                    :prop="'entryDriveways.' + index + '.drivewayName'"
                                    :rules="{
                                        required: true,
                                        message: '通道名称不能为空'
                                    }"
                                >
                                    <el-input v-model="item.drivewayName" placeholder="请输入"></el-input>
                                </el-form-item>
                                <el-form-item
                                    :label="'ip-' + (Number(index) + 1)"
                                    :prop="'entryDriveways.' + index + '.ip'"
                                    :rules="{
                                        required: true,
                                        message: '通道ip不能为空'
                                    }"
                                >
                                    <el-input v-model="item.ip" placeholder="请输入"></el-input>
                                </el-form-item>
                                <div class="delete-btn" v-if="!isEdit">
                                    <el-button @click.prevent="removeDriveway(item, 'entry')">删除</el-button>
                                </div>
                            </div>

                            <div class="handle-add" v-if="!isEdit">
                                <el-button type="primary" @click="addDriveway('entry')">新增</el-button>
                            </div>
                        </el-card>
                        <el-card class="box-card">
                            <div class="driveway-title">出口通道</div>
                            <div class="driveway-item" v-for="(item, index) in drivewayModal.exitDriveways" :key="index">
                                <el-form-item
                                    :label="'出口' + (Number(index) + 1)"
                                    :prop="'exitDriveways.' + index + '.drivewayName'"
                                    :rules="{
                                        required: true,
                                        message: '通道名称不能为空'
                                    }"
                                >
                                    <el-input v-model="item.drivewayName" placeholder="请输入"></el-input>
                                </el-form-item>
                                <el-form-item
                                    :label="'ip-' + (Number(index) + 1)"
                                    :prop="'exitDriveways.' + index + '.ip'"
                                    :rules="{
                                        required: true,
                                        message: '通道ip不能为空'
                                    }"
                                >
                                    <el-input v-model="item.ip" placeholder="请输入"></el-input>
                                </el-form-item>
                                <div class="delete-btn" v-if="!isEdit">
                                    <el-button @click.prevent="removeDriveway(item, 'exit')">删除</el-button>
                                </div>
                            </div>

                            <div class="handle-add" v-if="!isEdit">
                                <el-button type="primary" @click="addDriveway('exit')">+ 新增</el-button>
                            </div>
                        </el-card>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="nextStep" v-if="activeTab == 'parkInfo'">下一步</el-button>
                <el-button type="primary" @click="handleSubmit">保 存</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { saveParkInfo, parkList, saveDrivewayInfo, upDateParkInfo, drivewayInfoById, updateDrivewayInfo } from '@/api/park';
import { formatEnum } from '@/utils/tools';

const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    parkingLotName: ''
};

const parkForm = {
    parkingLotName: '',
    operateStatus: '',
    oneBusinessType: '',
    address: '',
    buildDate: '',
    operateDate: ''
};
const drivewayForm = {
    //通道信息表单对象
    entryDriveways: [{ drivewayName: '', ip: '' }], //入口
    exitDriveways: [{ drivewayName: '', ip: '' }] //出口，
};
export default {
    data() {
        return {
            modalRules: {
                parkingLotName: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
                operateStatus: [{ required: true, message: '该项为必填项' }],
                oneBusinessType: [{ required: true, message: '该项为必填项' }],
                address: [{ required: true, message: '该项为必填项' }],
                buildDate: [{ required: true, message: '该项为必填项' }],
                operateDate: [{ required: true, message: '该项为必填项' }]
            },
            firstBussinessOpt: [
                { label: '公建配套', value: 'PUBLIC_BUILD' },
                { label: '商办园区', value: 'BUSS_PARK' },
                { label: '交通枢纽', value: 'TRANS_HUB' },
                { label: '路侧', value: 'ROAD_SITE' }
            ],
            operateStatusOpt: [
                { label: '待建', value: 'TO_BE_BUILD' },
                { label: '施工', value: 'BUILDING' },
                { label: '运营', value: 'OPERATE' },
                { label: '故障', value: 'FAULT' },
                { label: '关闭', value: 'TEAR_DOWN' }
            ],
            listQuery: Object.assign({}, defaultListQuery),
            list: [],
            total: 0,
            listLoading: true,
            selectedList: [],
            myForm: {
                parkValue: ''
            },
            dialogFormVisible: false, //新增弹框
            modalForm: Object.assign({}, parkForm), //车场信息表单对象;
            drivewayModal: Object.assign({}, drivewayForm), //车场信息表单对象;, //表单对象;
            activeTab: 'parkInfo', //切换tab
            parkId: '', //当前停车场id;
            isEdit: false
        };
    },
    created() {
        this.getList();
    },
    methods: {
        closeModal() {
            // 置空表当
            this.activeTab = 'parkInfo';
            this.dialogFormVisible = false;
        },

        handleUpdate(index, row) {
            // 编辑
            this.parkId = row.parkingLotId;
            this.modalForm = {
                parkingLotName: row.parkingLotName,
                operateStatus: row.operateStatus,
                oneBusinessType: row.oneBusinessType,
                address: row.address,
                buildDate: row.buildDate,
                operateDate: row.operateDate
            };
            this.dialogFormVisible = true;
        },
        nextStep() {
            //如果没有维护停车场信息，提示
            if (!this.parkId) {
                this.$message.info('请先维护停车场信息');
                return false;
            }
            this.activeTab = 'drivewayInfo';
        },
        changeTab(tab, event) {
            console.log(this.parkId, 'ddd');

            if (!this.parkId) {
                this.$message.info('请先维护停车场信息');
                return false;
            }
            // //切换之前检验是否创建了停车场
            if (tab == 'drivewayInfo') {
                // 请求下当前是否有通道数据;
                drivewayInfoById({
                    parkingLotId: this.parkId
                }).then((result) => {
                    if (result.data) {
                        this.isEdit = true;
                        const entranceArray = [];
                        const exitArray = [];

                        // 遍历 data 数组
                        result.data.forEach((item) => {
                            const newItem = {
                                drivewayName: item.drivewayName,
                                ip: item.ip,
                                drivewayId: item.drivewayId
                            };
                            if (item.drivewayType === 'ENTRANCE') {
                                entranceArray.push(newItem); // 如果是入口，加入 entranceArray
                            } else if (item.drivewayType === 'EXIT') {
                                exitArray.push(newItem); // 如果是出口，加入 exitArray
                            }
                        });
                        this.drivewayModal = {
                            entryDriveways: entranceArray,
                            exitDriveways: exitArray
                        };
                    } else {
                        this.isEdit = false;
                    }
                });
            }
            return true;
        },
        addDriveway(type) {
            const newArray = type == 'entry' ? this.drivewayModal.entryDriveways : this.drivewayModal.exitDriveways;
            //新增一个通道
            newArray.push({
                drivewayName: ''
            });
        },
        removeDriveway(item, type) {
            // 删除一个通道
            const newArray = type == 'entry' ? this.drivewayModal.entryDriveways : this.drivewayModal.exitDriveways;
            var index = newArray.indexOf(item);
            if (index !== -1) {
                newArray.splice(index, 1);
            }
        },
        formatOpe(row, column, cellValue) {
            return formatEnum(this.operateStatusOpt, cellValue);
        },
        formatBus(ow, column, cellValue) {
            return formatEnum(this.firstBussinessOpt, cellValue);
        },
        async handleSubmit() {
            if (this.activeTab == 'parkInfo') {
                // 保存停车场信息
                this.$refs['modalForm'].validate(async (valid) => {
                    if (valid) {
                        const params = {
                            parkingLotName: this.modalForm.parkingLotName,
                            operateStatus: this.modalForm.operateStatus,
                            oneBusinessType: this.modalForm.oneBusinessType,
                            address: this.modalForm.address,
                            buildDate: this.modalForm.buildDate,
                            operateDate: this.modalForm.operateDate,
                            parkingLotId: this.parkId
                        };

                        const result = this.parkId ? await upDateParkInfo(params) : await saveParkInfo(params);
                        if (result.code == 200) {
                            // 保存成功之后赋值停车场iD;进行通道配置
                            this.parkId = result.data;
                            this.getList();
                            this.$message.success('保存成功');
                        } else {
                            this.$message.info(result.msg);
                        }
                    }
                    console.log(valid);
                });
                return;
                // 修改的是车场信息

                // 如果保存完之后会生成停车场id
            } else {
                // 修改的是通道信息
                this.drivewayModal.entryDriveways.map((item) => {
                    item.drivewayType = 'ENTRANCE';
                    item.parkingLotId = this.parkId;
                    item.drivewayId = item.drivewayId;
                });
                this.drivewayModal.exitDriveways.map((item) => {
                    item.drivewayType = 'EXIT';
                    item.parkingLotId = this.parkId;
                    item.drivewayId = item.drivewayId;
                });

                const newArr = [...this.drivewayModal.entryDriveways, ...this.drivewayModal.exitDriveways];
                const result = this.isEdit ? await updateDrivewayInfo(newArr) : await saveDrivewayInfo(newArr);

                if (result.code == 200) {
                    // 保存成功之后赋值停车场iD;进行通道配置
                    this.$message.success('保存成功');
                    this.listQuery.pageNum = 1;
                    this.getList();
                    this.dialogFormVisible = false;
                } else {
                    this.$message.info(result.msg);
                }
            }
        },
        handleSearch() {
            //搜索;
            this.listQuery.parkingLotName = this.myForm.parkValue;
            this.listQuery.pageNum = 1;
            this.getList();
        },
        handAdd() {
            //新增，将其他值设置为空
            this.parkId = '';
            this.dialogFormVisible = true;
            this.$refs['modalForm'].resetFields();
            this.$refs['drivewayModal'].resetFields();
            this.modalForm = Object.assign({}, parkForm); //车场信息表单对象;
            this.drivewayModal = Object.assign({}, drivewayForm); //车场信息表单对象;, //表单对象;
        },
        handleReset(formName) {
            //重置选项
            this.$refs[formName].resetFields();
            this.listQuery = Object.assign({}, defaultListQuery); // 清空输入框内容
            this.getList(); // 刷新列表并初始化
        },
        handleSizeChange(val) {
            // 改变列表显示条数
            this.listQuery.pageNum = 1;
            this.listQuery.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            // 改变列表显示页数
            this.listQuery.pageNum = val;
            this.getList();
        },

        getList() {
            // 获取数据列表
            this.listLoading = true;
            parkList(this.listQuery)
                .then((res) => {
                    this.listLoading = false;
                    this.list = res.data.records;
                    this.total = Number(res.data.total);
                })
                .catch((err) => {
                    this.listLoading = false;
                });
        }
    }
};
</script>
<style scoped>
.handle-add {
    width: 100%;
    height: 78px;
    border: 1px dashed rgba(47, 143, 241, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
    border-radius: 8px;
}
.driveway-title {
    margin-bottom: 20px;
}

.park-info ::v-deep .el-input,
.park-info ::v-deep .el-select {
    width: 300px !important;
}
.driveway-item {
    display: flex;
}
.delete-btn {
    margin-left: 10px;
}
</style>
